package ioc

import (
	"errors"
)

// AopProxy  aop的代理接口
type AopProxy interface {
	// GetOriginBean 获取代理的bean
	GetOriginBean() interface{}

	// SetOriginBean 设置代理bean
	SetOriginBean(t interface{})
}

// RegisterAop  注册aop拦截，并替换;targetBeanId必须存在,若不存在也没必要注册aop拦截，直接在注册前创建代理就行了
func RegisterAop[T any](proxyBean *T, targetBeanId string) error {
	if proxyBean == nil {
		return errors.New("proxyBean is nil")
	}

	if Is[AopProxy](proxyBean) {
		return errors.New("proxyBean must implements AopProxy")
	}

	targetBean, err := GetById[T](targetBeanId)
	if err != nil {
		return err
	}

	aopBean, _ := ToType[AopProxy](proxyBean)
	aopBean.SetOriginBean(targetBean)

	container.Set(targetBeanId, aopBean)

	return nil
}
